
export function createConstants(...constants) {
    return constants.reduce((acc, constant) => {
        acc[constant] = constant;
        return acc;
    }, {});
}

export function createReducer(initialState, reducerMap) {
    return (state = initialState, action) => {
        const reducer = reducerMap[action.type];
        return reducer
            ? reducer(state, action.payload) : state;
    };
}

export function checkHttpStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response
    } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
    }
}

export function parseJSON(response) {
     return response.json()

}

export function fetchApiWithPost(url, argus, dispatch, SUCC_TYPE, FAIL_TYPE) {
    return fetch(url, {
             method: 'POST',
             headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(argus)
        })
        .then(checkHttpStatus)
        .then(parseJSON)
        .then(
            response => {
                if(response.status == 1) {
                    dispatch({
                        type: SUCC_TYPE,
                        payload: {
                            data: response.content!=undefined ? response.content: response.data
                        }
                    });
                }else {
                    dispatch({
                        type: FAIL_TYPE
                    });
                    console.log(response.errmsg);
                }
            },
            error => {
                console.log('fetching API fails:' + error);
            }
        )
}

export function fetchApiWithGet(url, dispatch, SUCC_TYPE, FAIL_TYPE) {
    return fetch(url, {
             method: 'GET',
             headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then(checkHttpStatus)
        .then(parseJSON)
        .then(
            response => {
                if(response.status == 1) {
                    dispatch({
                        type: SUCC_TYPE,
                        payload: {
                            data: response.content.data!=undefined ? response.content.data : []
                        }
                    });
                }else {
                    dispatch({
                        type: FAIL_TYPE
                    });
                    console.log(response.errmsg);
                }
            },
            error => {
                console.log('fetching API fails:' + error);
            }
        )
}
